# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)
library(NormalizeMets)

option_list <- list(
  make_option("--si", default = "1;0", type = "character", help = "step"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

si <- opt$si %>%
  str_split(";") %>%
  unlist()
step <- si[1] %>%
  as.numeric()

data <- read_tsv(str_c(step - 1, ".result.txt")) %>%
  rename(Metabolite = 1)

featureData <- data %>%
  gather("SampleID", "Value", -Metabolite, factor_key = T) %>%
  spread(Metabolite, "Value") %>%
  column_to_rownames("SampleID")

sampleData <- read_tsv(opt$g) %>%
  rename(SampleID = 1) %>%
  select(c("SampleID", "ClassNote")) %>%
  rename(class = ClassNote) %>%
  arrange(factor(SampleID, levels = rownames(featureData))) %>%
  mutate(batch = 1, order = 1:n()) %>%
  mutate(class = str_replace(class, "QC", "0")) %>%
  column_to_rownames("SampleID")

Norm_rlsc <- NormQcsamples(featureData, sampleData, lg = FALSE, span = 0.75)

outData <- Norm_rlsc$featuredata %>%
  as_tibble() %>%
  mutate(SampleID = rownames(featureData)) %>%
  mutate(SampleID = factor(SampleID, levels = unique(SampleID))) %>%
  gather("Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value") %>%
  mutate(Metabolite=data$Metabolite)

outData

write_tsv(outData, str_c(step, ".result.txt"))
write_csv(outData, str_c(step, ".loess.csv"))








